/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MaintenanceRepairListFragment.java   
 * @Package com.jiyi.activity.new_maintenance.repair   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-27 上午11:19:41   
 * @version V1.0     
 */
package com.jiyi.activity.leader.repair;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.leader.LeaderViewReportActivity;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.MultiItemTypeAdapter;
import com.jiyi.adapter.recyclerview.base.ItemViewDelegate;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.maintenance.MantenanceRepairBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.ErrorTaskListEvent;
import com.jiyi.inteface.ConfirmPopInterface;
import com.jiyi.inteface.OnRcvScrollListener;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.ConfirmPopView;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DialogTool;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: LeaderMaintenanceRepairListFragment
 * @Description:TODO(主管的)
 * @author: HYM
 * @date: 2017-11-6 上午10:16:24
 * 
 */
public class LeaderMaintenanceRepairListFragment extends Fragment implements
		OnRefreshListener, ConfirmPopInterface {

	LayoutInflater inflater;
	@BindView(R.id.mainList)
	RecyclerView mListView;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	EmptyWrapper adapter;
	ViewGroup container;
	int type;
	private List<MantenanceRepairBean> dataList = new ArrayList<MantenanceRepairBean>();
	Dialog dialog;

	// 是否刷新模式
	boolean isRefresh = false;
	int pageNo = 1;// 页码
	private final int LOAD_DATA = 5; // 加载数据事件
	private boolean loadfinish = true; // 指示数据是否加载完成
	ConfirmPopView mConfirmPopView;
	// 要被删除的任务
	int deletePosition = -1;
	// 要被删除的BID
	String deleteBid = "";

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater
				.inflate(R.layout.fragment_all_wx_task, null, false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		this.container = container;
		init();
		return view;
	}

	private void init() {
		getIntentData();
		setAdapter();
		onRefresh();
		mConfirmPopView = new ConfirmPopView(getContext(), this, "确定撤回派发出的任务？",
				"不撤销", "撤销派发");
	}

	private void getIntentData() {
		type = getArguments().getInt("type", 0);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mListView.setLayoutManager(new LinearLayoutManager(getContext()));
		mListView.addItemDecoration(new DividerItemDecoration(getContext(),
				DividerItemDecoration.VERTICAL_LIST, getResources()
						.getDrawable(R.drawable.drvice_10)));

		MultiItemTypeAdapter multiItemTypeAdapter = new MultiItemTypeAdapter(
				getContext(), dataList);
		multiItemTypeAdapter.addItemViewDelegate(new WaitDeclareDelagate());
		multiItemTypeAdapter.addItemViewDelegate(new WaitCheckDelagate());
		multiItemTypeAdapter.addItemViewDelegate(new HasVetoDelagate());
		multiItemTypeAdapter.addItemViewDelegate(new WaitRepairDelagate());
		multiItemTypeAdapter.addItemViewDelegate(new HasFinishDelagate());

		adapter = new EmptyWrapper(multiItemTypeAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				container, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		mListView.addOnScrollListener(new OnRcvScrollListener() {
			@Override
			public void onBottom() {
				super.onBottom();
				if (loadfinish) {
					Log.e("加载到底部 pageNo = ", pageNo + "");
					Log.e("加载到底部 list size = ", dataList.size() + "");
					loadMore();
				}

			}
		});
	}

	public class WaitDeclareDelagate implements
			ItemViewDelegate<MantenanceRepairBean> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_owner_repair_wait_declare;
		}

		@Override
		public boolean isForViewType(MantenanceRepairBean item, int position) {
			return item.getType() == 0;
		}

		@Override
		public void convert(final ViewHolder holder,
				final MantenanceRepairBean task, final int position) {
			holder.setText(R.id.tvCompany, task.getCompany_name());
			holder.setText(R.id.tvErrorDate, task.getError_time());
			holder.setText(R.id.tvRepairDate, task.getExpect_date());
			holder.setText(
					R.id.tvLeader,
					TextUtils.isEmpty(task.getPayout_name()) ? task
							.getUser_name() : task.getPayout_name());
			holder.setText(R.id.tvRemark, task.getZg_comments());
			holder.setVisible(R.id.rlDesc, true);
			holder.setRepairTaskAdapter(R.id.childListView, task.getGetInfo(),
					type, position);
			holder.setOnClickListener(R.id.rlExtend, new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (v.getTag() == null) {
						holder.setVisible(R.id.childListView, true);
						v.setTag("extend");
					} else {
						holder.setVisible(R.id.childListView, false);
						v.setTag(null);
					}
				}
			});

			if (task.getTemp_inspection() == 0) {
				// 正常保存
				holder.setVisible(R.id.llErrorDate, true);
				holder.setVisible(R.id.rlExtend, true);
				holder.setVisible(R.id.llMalfunctionItem, true);
			} else {
				// 临检报修
				holder.setVisible(R.id.llErrorDate, false);
				holder.setVisible(R.id.rlExtend, false);
				holder.setVisible(R.id.llMalfunctionItem, false);
			}

			if (task.getIs_receive() == 0) {
				// 未接收
				holder.setText(R.id.tvDesc, "待接收");
				holder.setVisible(R.id.tvDelete, true);
			} else {
				// 已接收
				holder.setText(R.id.tvDesc, "待申报");
				holder.setVisible(R.id.tvDelete, false);
			}

			holder.setOnClickListener(R.id.tvDelete, new OnClickListener() {

				@Override
				public void onClick(View v) {
					deleteBid = task.getBid();
					deletePosition = position;
					mConfirmPopView.showPopWindow();
				}
			});
		}
	}

	public class WaitCheckDelagate implements
			ItemViewDelegate<MantenanceRepairBean> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_repair_wait_check;
		}

		@Override
		public boolean isForViewType(MantenanceRepairBean item, int position) {
			return item.getType() == 1;
		}

		@Override
		public void convert(final ViewHolder holder,
				final MantenanceRepairBean task, int position) {
			holder.setText(R.id.tvCompany, task.getCompany_name());
			holder.setText(R.id.tvErrorDate, task.getError_time());
			holder.setText(R.id.tvRepairDate, task.getExpect_date());
			holder.setText(
					R.id.tvLeader,
					TextUtils.isEmpty(task.getPayout_name()) ? task
							.getUser_name() : task.getPayout_name());
			holder.setText(R.id.tvRemark, task.getZg_comments());

			holder.setRepairTaskAdapter(R.id.childListView, task.getGetInfo(),
					type, position);
			holder.setOnClickListener(R.id.rlExtend, new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (v.getTag() == null) {
						holder.setVisible(R.id.childListView, true);
						v.setTag("extend");
					} else {
						holder.setVisible(R.id.childListView, false);
						v.setTag(null);
					}
				}
			});

			if (task.getTemp_inspection() == 0) {
				// 正常保存
				holder.setVisible(R.id.llErrorDate, true);
				holder.setVisible(R.id.rlExtend, true);
				holder.setVisible(R.id.llMalfunctionItem, true);
			} else {
				// 临检报修
				holder.setVisible(R.id.llErrorDate, false);
				holder.setVisible(R.id.rlExtend, false);
				holder.setVisible(R.id.llMalfunctionItem, false);
			}

			holder.setOnClickListener(R.id.tvView, new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(),
							LeaderViewReportActivity.class);
					intent.putExtra("type", 2);
					intent.putExtra("ownerId", task.getCompany_id());
					intent.putExtra("bid", task.getBid());
					v.getContext().startActivity(intent);
				}
			});

			if (task.getGetInfo() != null && task.getGetInfo().size() > 0) {
				holder.setVisible(R.id.llCheckReportView, true);
			} else {
				holder.setVisible(R.id.llCheckReportView, false);
			}
		}
	}

	public class HasVetoDelagate implements
			ItemViewDelegate<MantenanceRepairBean> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_owner_repair_has_vote;
		}

		@Override
		public boolean isForViewType(MantenanceRepairBean item, int position) {
			return item.getType() == 2;
		}

		@Override
		public void convert(final ViewHolder holder,
				final MantenanceRepairBean task, final int position) {
			holder.setText(R.id.tvCompany, task.getCompany_name());
			holder.setText(R.id.tvErrorDate, task.getError_time());
			holder.setText(R.id.tvRepairDate, task.getExpect_date());
			holder.setText(
					R.id.tvLeader,
					TextUtils.isEmpty(task.getPayout_name()) ? task
							.getUser_name() : task.getPayout_name());
			holder.setText(R.id.tvRemark, task.getZg_comments());

			holder.setRepairTaskAdapter(R.id.childListView, task.getGetInfo(),
					type, position);
			holder.setOnClickListener(R.id.rlExtend, new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (v.getTag() == null) {
						holder.setVisible(R.id.childListView, true);
						v.setTag("extend");
					} else {
						holder.setVisible(R.id.childListView, false);
						v.setTag(null);
					}
				}
			});

			if (task.getTemp_inspection() == 0) {
				// 正常保存
				holder.setVisible(R.id.llErrorDate, true);
				holder.setVisible(R.id.rlExtend, true);
				holder.setVisible(R.id.llMalfunctionItem, true);
			} else {
				// 临检报修
				holder.setVisible(R.id.llErrorDate, false);
				holder.setVisible(R.id.rlExtend, false);
				holder.setVisible(R.id.llMalfunctionItem, false);
			}

			holder.setOnClickListener(R.id.tvView, new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(),
							LeaderViewReportActivity.class);
					intent.putExtra("type", 2);
					intent.putExtra("ownerId", task.getCompany_id());
					intent.putExtra("bid", task.getBid());
					v.getContext().startActivity(intent);
				}
			});

			if (task.getGetInfo() != null && task.getGetInfo().size() > 0) {
				holder.setVisible(R.id.llCheckReportView, true);
			} else {
				holder.setVisible(R.id.llCheckReportView, false);
			}
		}
	}

	public class WaitRepairDelagate implements
			ItemViewDelegate<MantenanceRepairBean> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_owner_repair_wait_repair;
		}

		@Override
		public boolean isForViewType(MantenanceRepairBean item, int position) {
			return item.getType() == 3;
		}

		@Override
		public void convert(final ViewHolder holder,
				final MantenanceRepairBean task, int position) {
			holder.setText(R.id.tvCompany, task.getCompany_name());
			holder.setText(R.id.tvErrorDate, task.getError_time());
			holder.setText(R.id.tvRepairDate, task.getExpect_date());
			holder.setText(
					R.id.tvLeader,
					TextUtils.isEmpty(task.getPayout_name()) ? task
							.getUser_name() : task.getPayout_name());
			holder.setText(R.id.tvRemark, task.getZg_comments());

			holder.setRepairTaskAdapter(R.id.childListView, task.getGetInfo(),
					type, position);
			holder.setRepairProgressAdapter(R.id.commentListView, task.getSchedule(),type, position);
			holder.setOnClickListener(R.id.rlExtend, new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (v.getTag() == null) {
						holder.setVisible(R.id.childListView, true);
						v.setTag("extend");
					} else {
						holder.setVisible(R.id.childListView, false);
						v.setTag(null);
					}
				}
			});

			if (task.getTemp_inspection() == 0) {
				// 正常保存
				holder.setVisible(R.id.llErrorDate, true);
				holder.setVisible(R.id.rlExtend, true);
				holder.setVisible(R.id.llMalfunctionItem, true);
			} else {
				// 临检报修
				holder.setVisible(R.id.llErrorDate, false);
				holder.setVisible(R.id.rlExtend, false);
				holder.setVisible(R.id.llMalfunctionItem, false);
			}

			holder.setOnClickListener(R.id.tvView, new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(),
							LeaderViewReportActivity.class);
					intent.putExtra("type", 2);
					intent.putExtra("ownerId", task.getCompany_id());
					intent.putExtra("bid", task.getBid());
					v.getContext().startActivity(intent);
				}
			});

			if (task.getGetInfo() != null && task.getGetInfo().size() > 0) {
				holder.setVisible(R.id.llCheckReportView, true);
			} else {
				holder.setVisible(R.id.llCheckReportView, false);
			}

		}
	}

	public class HasFinishDelagate implements
			ItemViewDelegate<MantenanceRepairBean> {

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_repair_has_finish;
		}

		@Override
		public boolean isForViewType(MantenanceRepairBean item, int position) {
			return item.getType() == 4;
		}

		@Override
		public void convert(final ViewHolder holder,
				final MantenanceRepairBean task, int position) {
			holder.setText(R.id.tvCompany, task.getCompany_name());
			holder.setText(R.id.tvErrorDate, task.getError_time());
			holder.setText(R.id.tvRepairDate, task.getExpect_date());
			holder.setText(
					R.id.tvLeader,
					TextUtils.isEmpty(task.getPayout_name()) ? task
							.getUser_name() : task.getPayout_name());
			holder.setText(R.id.tvRemark, task.getZg_comments());
			holder.setText(R.id.tvFinishComments, task.getComments());
			holder.setRepairTaskAdapter(R.id.childListView, task.getGetInfo(),
					type, position);
			holder.setRepairProgressAdapter(R.id.commentListView, task.getSchedule(),type, position);
			holder.setOnClickListener(R.id.rlExtend, new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (v.getTag() == null) {
						holder.setVisible(R.id.childListView, true);
						v.setTag("extend");
					} else {
						holder.setVisible(R.id.childListView, false);
						v.setTag(null);
					}
				}
			});

			if (task.getTemp_inspection() == 0) {
				// 正常报错
				holder.setVisible(R.id.llErrorDate, true);
				holder.setVisible(R.id.rlExtend, true);
				holder.setVisible(R.id.llMalfunctionItem, true);

			} else {
				// 临检报修
				holder.setVisible(R.id.llErrorDate, false);
				holder.setVisible(R.id.rlExtend, false);
				holder.setVisible(R.id.llMalfunctionItem, false);

			}

			if (task.getGetInfo() != null && task.getGetInfo().size() > 0) {
				holder.setVisible(R.id.llRemark, false);
				holder.setVisible(R.id.llCheckReportView, true);
			} else {
				holder.setVisible(R.id.llRemark, true);
				holder.setVisible(R.id.llCheckReportView, false);
			}

			holder.setOnClickListener(R.id.tvView, new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(v.getContext(),
							LeaderViewReportActivity.class);
					intent.putExtra("type", 2);
					intent.putExtra("ownerId", task.getCompany_id());
					intent.putExtra("bid", task.getBid());
					v.getContext().startActivity(intent);
				}
			});
		}
	}

	/**
	 * @author: HYM
	 * @Title: doDeclare
	 * @Description: TODO(申报动作)
	 * @param cfid
	 * @param position
	 * @param type
	 *            void
	 * @date: 2017-9-25
	 */
	void doDeclare(String cfid, final int position, final int type) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("cfid", cfid);

		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_LEADER_ERROR_TASK_LIST_DECLARE, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								EventBus.getDefault().post(
										new ErrorTaskListEvent(type, position,
												1));
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							// hideDialog(dialog);
						}

					}

					@Override
					public void stringError(VolleyError error) {
						// hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}
	
	
	/**   
	 * @author: HYM 
	 * @Title: doDelete   
	 * @Description: TODO(主管撤回派发任务)   
	 * @param bid
	 * @param position void
	 * @date: 2017-11-14
	 */  
	void doDelete(String bid, final int position) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("bid", bid);
		dialog = DialogTool.showDialog(dialog, getContext());
		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_LEADER_DELETE_NO_RECIVE_WXTASK, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								dataList.remove(position);
								adapter.notifyDataSetChanged();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							DialogTool.hideDialog(dialog);
						}

					}

					@Override
					public void stringError(VolleyError error) {
						DialogTool.hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("type", type + "");
		params.put("p", pageNo + "");
		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_ALL_REPAIR, "", params, new StringInterface(
						getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<MantenanceRepairBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<MantenanceRepairBean>>() {
												}.getType());
								if (isRefresh) {
									dataList.clear();
								}

								if (temp.size() > 0) {
									dataList.addAll(temp);
									pageNo++;
								} else {

								}
								adapter.notifyDataSetChanged();
								loadfinish = true;
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	@Override
	public void onRefresh() {
		isRefresh = true;
		pageNo = 1;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}

	/**
	 * 处理中心
	 */
	Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case LOAD_DATA:
				if (loadfinish) {
					loadfinish = false;
					getData();
				}
				break;
			default:
				break;
			}
		};
	};

	/**
	 * 作者：hym 日期：2017-4-6 描述：加载更多数据
	 */
	void loadMore() {
		isRefresh = false;
		mHandler.sendEmptyMessage(LOAD_DATA);
	}

	@Override
	public void OnDeleteListener() {
		doDelete(deleteBid, deletePosition);
		mConfirmPopView.hidePopWindow();
	}

	@Override
	public void OnCancleListener() {
	}

	@Override
	public void OnShowListener() {
		
	}

	@Override
	public void OnHideListener() {
		deleteBid = "";
		deletePosition = -1;
	}
}
